﻿#region Copyright

//  ======================================================
//      Copyright (c) 2011 Toulr All rights reserved.
//     
//      The use and distribution terms for this software are contained in the file
//      named license.txt, which can be found in the root of this distribution.
//      By using this software in any fashion, you are agreeing to be bound by the
//      terms of this license.
//     
//     You must not remove this notice, or any other, from this software.
//  ======================================================

#endregion

#region Using Namespaces

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Resources;
using Toulr.Core.Resource;
using Toulr.Domains;
using Toulr.Domains.Business;
using Toulr.Domains.System;
using Toulr.Models;
using Toulr.Models.Enums;
using Toulr.Services;
using Toulr.Util.Security;

#endregion

namespace Toulr.Core.Services
{
    public class ApplicationContextService : IApplicationContextService
    {
        protected static ResourceManager MessagesResourceManager = Messages.ResourceManager;

        public static CultureInfo DefaultCultureInfo
        {
            get { return new CultureInfo("zh-CN", false); }
        }

        public CultureInfo CurrentCultureInfo { get; set; }

        #region IApplicationContextService Members

        ActionResult<VerifyImage> IApplicationContextService.GetVerifyCode()
        {
            var verifyImage = new VerifyImage();
            verifyImage.Code = VerifyCodeHelper.NextCode(4);
            verifyImage.Image = VerifyCodeHelper.NextImage(verifyImage.Code);
            return new ActionResult<VerifyImage>(0, "", verifyImage);
        }

        /// <summary>
        ///   获取当前Enable为True的省份列表，注意这里的省份列表内同时级联包括了城市信息
        /// </summary>
        /// <returns></returns>
        /// Author: James Cheung
        /// MachineName: JAMESCHEUNG-PC
        /// DateTime: 2011/5/11 22:54
        public ActionResult<IList<Province>> GetProvinces()
        {
            var obj = from e in DomainContext.Instance.Provinces
                      where e.Enabled
                      select e;
            var u = obj.ToArray();
            IList<Province> provinces = new List<Province> {};
            foreach (var p in u)
            {
                provinces.Add(p);
            }
            return new ActionResult<IList<Province>>(0, "成功获取省份信息", provinces);
        }

        #endregion

        #region 快递公司相关操作

        public IList<ExpressDelivery> GetExpressDeliverys(int id, string name, bool? enabled)
        {
            //ToDo 单个表的多条件查询写法1
            var obj = from ed in DomainContext.Instance.ExpressDeliveries
                      select ed;

            if (enabled != null)
            {
                obj = obj.Where(ed => ed.Enabled == enabled);
            }
            if (id != -1)
            {
                obj = obj.Where(en => en.Id == id);
            }
            if (!string.IsNullOrEmpty(name))
            {
                obj = obj.Where(en => en.Name.Contains(name));
            }

            return obj.ToArray();
        }


        private ExpressDelivery GetExpressDelivery(int id, string name, bool? enabled)
        {
            IList<ExpressDelivery> lstExpressDelivery= GetExpressDeliverys(id, name, enabled);
            if (lstExpressDelivery.Count > 0)
                return lstExpressDelivery[0];
            return null;
        }

        public ActionResult<IList<ExpressDelivery>> GetExpressDeliverys()
        {
            try
            {
                IList<ExpressDelivery> lstExpressDelivery = GetExpressDeliverys(-1, null, true);

                return new ActionResult<IList<ExpressDelivery>>(0, "获取快递公司列表成功", lstExpressDelivery);
            }
            catch (Exception ex)
            {
                //todo 记录错误日志
                return new ActionResult<IList<ExpressDelivery>>(1, ex.Message, null);
            }
        }

        /// <summary>
        ///   添加快递公司信息
        /// </summary>
        /// <param name = "expressDelivery"></param>
        /// <returns></returns>
        /// hyyu 20110514
        public ActionResult<ExpressDelivery> AddExpressDelivery(ExpressDelivery expressDelivery)
        {
            if (expressDelivery == null)
            {
                return new ActionResult<ExpressDelivery>(1, "没有要添加的快递公司信息", null);
            }
            if (string.IsNullOrEmpty(expressDelivery.Name))
            {
                return new ActionResult<ExpressDelivery>(1, "快递公司名称不能为空", null);
            }
            if (GetExpressDelivery(-1, expressDelivery.Name, null) != null)
            {
                return new ActionResult<ExpressDelivery>(1, "快递公司名称重复", null);
            }
            try
            {
                expressDelivery.Id = GetMaxExpressDeliveryId();
                var repository = new Repository<ExpressDelivery>();
                repository.Add(expressDelivery);
                return new ActionResult<ExpressDelivery>(0, "快递公司信息保存成功", expressDelivery);
            }
            catch (Exception ex)
            {
                //todo 记录错误日志
                return new ActionResult<ExpressDelivery>(1, ex.Message, null);
            }
        }

        /// <summary>
        ///   修改快递公司信息
        /// </summary>
        /// <param name = "expressDelivery"></param>
        /// <returns></returns>
        /// hyyu 20110514
        public ActionResult<ExpressDelivery> UpdateExpressDelivery(ExpressDelivery expressDelivery)
        {
            try
            {
                if (expressDelivery == null)
                {
                    return new ActionResult<ExpressDelivery>(1, "要修改的快递公司信息为空", null);
                }
                if (expressDelivery.Id <= 0)
                {
                    return new ActionResult<ExpressDelivery>(1, "要修改的快递公司编号不能为空", null);
                }
                var curObj = GetExpressDelivery(expressDelivery.Id, null, null);
                if (curObj == null)
                {
                    return new ActionResult<ExpressDelivery>(1, "没有找到指定的快递公司信息", null);
                }

                var repository = new Repository<ExpressDelivery>();
                repository.Update(expressDelivery);
                return new ActionResult<ExpressDelivery>(0, "修改快递公司信息成功", expressDelivery);
            }
            catch (Exception ex)
            {
                //todo 记录错误日志
                return new ActionResult<ExpressDelivery>(1, ex.Message, null);
            }
        }

        /// <summary>
        ///   删除快递公司信息
        /// </summary>
        /// <param name = "expressDelivery"></param>
        /// <returns></returns>
        /// hyyu 20110514
        public ActionResult<ExpressDelivery> DeleteExpressDelivery(ExpressDelivery expressDelivery)
        {
            //ToDo 此处应该级联删除对应的定单？或者修改数据库表，增加标识位，表示快递公司是否已经停用
            if (expressDelivery == null)
            {
                return new ActionResult<ExpressDelivery>(1, "要删除的快递公司信息为空", null);
            }
            if (expressDelivery.Id <= 0)
            {
                return new ActionResult<ExpressDelivery>(1, "要删除的快递公司编号不能为空", null);
            }
            var curObj = GetExpressDelivery(expressDelivery.Id, null, null);
            if (curObj == null)
            {
                return new ActionResult<ExpressDelivery>(1, "没有找到要删除快递公司的信息", null);
            }
            try
            {
                var repository = new Repository<ExpressDelivery>();
                repository.Delete(curObj);
                return new ActionResult<ExpressDelivery>(0, "删除快递公司信息成功", expressDelivery);
            }
            catch (Exception ex)
            {
                //todo 记录错误日志
                return new ActionResult<ExpressDelivery>(1, ex.Message, null);
            }
        }

        private static int GetMaxExpressDeliveryId()
        {
            var obj = from ed in DomainContext.Instance.ExpressDeliveries
                      select ed;
            int count = obj.Count();
            if (count == 0)
                return 1;

            int maxId = obj.Max(ed => ed.Id);

            return maxId + 1;
        }

        #endregion

        /// <summary>
        ///   获取资源字符
        /// </summary>
        public String GetMessageString(String keyName)
        {
            return MessagesResourceManager.GetString(keyName, CurrentCultureInfo);
        }

    }
}